﻿using System;
using CoreComponents.DataAccess;
using Crowler.Model.CoreComponents.DataAccess;
using Crowler.TestBase;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NHibernate;


namespace Crowler.CoreComponents.Test
{
    [TestClass]
    public class DataAccessManagerShould:TestBaseClass
    {
        private Mock<IUnitOfWorkFactory> _unitOfWorkFactory;
        private Mock<IUnitOfWork> _unitOfWorkMock;
        private DataAccessManager _dataAccessManager;
        public override void TestCleanup()  {}

        public override void TestInitialize()
        {
            _unitOfWorkFactory = new Mock<IUnitOfWorkFactory>();
            _unitOfWorkMock = new Mock<IUnitOfWork>();
            _dataAccessManager = new DataAccessManager(_unitOfWorkFactory.Object);
            SetUpMocks();
        }

        private void SetUpMocks()
        {
            _unitOfWorkFactory.Setup(o => o.Create()).Returns(_unitOfWorkMock.Object);
            _unitOfWorkFactory.Setup(o => o.CurrentSession).Returns(new Mock<ISession>().Object);
        }

        [TestMethod]
        public void StartUnitOfWork()
        {
            _dataAccessManager.Start();
            _unitOfWorkFactory.Verify(o => o.Create(),Times.Once());
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void ThrowExceptionIfUnitOfWorkAlreadyStarted()
        {
            _dataAccessManager.Start();
            _dataAccessManager.Start();
        }

        [TestMethod]
        public void AccessExistingUnitOfWork()
        {
            var initial = _dataAccessManager.Start();
            var same = _dataAccessManager.Current;
            Assert.AreEqual(initial,same);
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void ThrowExceptionIfCurrentNotExist()
        {
            var uow = _dataAccessManager.Current;

        }

        [TestMethod]
        public void NotifyIfCurrentUowStarted()
        {
            Assert.AreEqual(false,_dataAccessManager.IsStarted);
            _dataAccessManager.Start();
            Assert.AreEqual(true, _dataAccessManager.IsStarted);
        }

        [TestMethod]
        public void GetValidCurrentSessionIfUoWIsStarted()
        {
            var session = _dataAccessManager.CurrentSession;
            Assert.IsNotNull(session);
        }
       
    }
}
